package com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30;

import com.caiyi.financial.nirvana.sms.gateway.cmpp.CMPPHeader;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30.message.CMPP3Body;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30.message.CMPP3Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class CMPP3StreamDecoder extends ByteToMessageDecoder {
    private static final Logger logger = LoggerFactory.getLogger(CMPP3StreamDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext context, ByteBuf buff, List<Object> out) throws Exception {
        if (buff.readableBytes() <= 0) {
            return;
        }
        try {
            CMPP3Message message = new CMPP3Message();

            CMPPHeader header = new CMPPHeader();
            header.decode(buff);
            message.setHeader(header);
            try {
                CMPP3Body body = CMPP3Body.decodeBody(message.getCommandID(), buff);
                message.setBody(body);
                message.setDecodeSuccess(true);
            } catch (Exception e) {
                logger.error("cmpp30 decode error!", e);
                message.setDecodeSuccess(false);
            }
            out.add(message);
            if (buff.readableBytes() > 0) {
                logger.error("cmpp30 decode have remain bytes:" + ByteBufUtil.prettyHexDump(buff));
                logger.error("解码消息:" + message.toString());
                byte[] temp = new byte[buff.readableBytes()];
                buff.readBytes(temp);
            }
        } catch (Exception e) {
            logger.error("cmpp30 decode error!", e);
        }
    }
}
